﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Threading;
using Board1.Info;
using Board1.GetData;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
namespace Board1.UIPage
{
    public partial class SongPage : PhoneApplicationPage
    {
        private int index;
        public static int pageID = 0;
        WebClient download = new WebClient();
        string webData;
        private ObservableCollection<SongData> listSong;

        private static ObservableCollection<ZingSong> _listResult;
        public static ObservableCollection<ZingSong> ListResult
        { get { return _listResult; } }
        public SongPage()
        {
            InitializeComponent();
            index = MainPage.indexSongSelected;
            listSong = DataHot100.TopHot100Songs;
            this.DataContext = listSong[index];
        }

        // bat su kien flick tren man hinh
        private void GestureListener_Flick_1(object sender, FlickGestureEventArgs e)
        {
            //left
            if (e.HorizontalVelocity >= 0)
            {
                if (index > 0)
                {
                    index--;
                }
                else
                {
                    index = listSong.Count - 1;
                }

            }
            //right
            else
            {
                if (index < listSong.Count - 1)
                {
                    index++;
                }
                else
                {
                    index = 0;
                }
            }
            DataContext = listSong[index];
        }

        // tao su kien khi click vao app bar
        private void appBarZingMP3_Click_1(object sender, EventArgs e)
        {
            _listResult= new ObservableCollection<ZingSong>();
            string keyWord = (listSong[index].songName +"+"+ listSong[index].artistName).Replace(" ","+");
            webData = null;
            ThreadPool.QueueUserWorkItem(o =>
            {
                Dispatcher.BeginInvoke(new Action(() => DownloadData(keyWord)));
                Dispatcher.BeginInvoke(new Action(() => LoadingState(false)));
                Thread.Sleep(3000);
            }
                );
            //DownloadData(keyWord);
        }

        // tai du lieu tim kiem bai hat tu mp3 zing
        private void DownloadData(string key)
        {
            key = "http://mp3.zing.vn/tim-kiem/bai-hat.html?q=" + key;
            try 
            {
                download.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallBack);
                download.DownloadStringAsync(new Uri(key));
            }
            catch(System.Exception)
            {}
        }

        private void DownloadStringCallBack(object sender, DownloadStringCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                webData = (string)e.Result;
                HtmlHander(webData);
                ListResultSong.PageID = pageID;
                this.NavigationService.Navigate(new Uri("/UIPage/ListResultSong.xaml", UriKind.Relative));
            }
        }

        // xu li du lieu html de lay noi dung
        private void HtmlHander(string data)
        {
            MatchCollection content = Regex.Matches(data, "<a class=\"_trackLink\" tracking=\"_frombox=search_song\" title=(.*?)-(.*?) href=(.*?)>(.*?)</a>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            foreach (Match m in content)
            {
                ZingSong newItem = new ZingSong();
                string name = m.Groups[1].ToString().Replace("\"", "");
                newItem.song = name.Replace("&amp;", "&");
                string artist = m.Groups[2].ToString().Replace("\"", "");
                newItem.artist = artist.Replace("&amp;", "&");
                string link = "http://mp3.zing.vn" + m.Groups[3].ToString().Replace("\"", "");
                newItem.link = link;
                _listResult.Add(newItem);
            }
        }
        private void LoadingState(bool e)
        {
            if (e)
            {
                LoadState1.Visibility = Visibility.Visible;
                LoadBar1.Visibility = Visibility.Visible;
                LoadBar1.IsIndeterminate = e;
            }
            else
            {
                LoadState1.Visibility = Visibility.Collapsed;
                LoadBar1.Visibility = Visibility.Collapsed;
                LoadBar1.IsIndeterminate = e;
            }
        }
    }
}